'use strict'

import React from 'react'
import { message } from 'antd'
import { CopyOutlined } from '@ant-design/icons'

/**
 * 复制文字到剪切板
 * @param {String} val 待复制的值
 * @param {Boolean} showMessage 是否需要提示复制成功
 */
export const setCopy = function (val, showMessage = true) {
  const input = document.createElement('textarea')
  input.innerHTML = val || ''
  document.body.appendChild(input)
  input.select()
  const result = document.execCommand('copy')
  document.body.removeChild(input)
  showMessage && message.success('复制成功')
  return result
}

/**
 * 复制文字到剪切板组件
 * @param {String} props.text 显示文字
 * @param {String} props.copyText 复制文字，如果不传默认用props.text
 */
export default function CopyText(props) {
  return (
    <span>
      <span style={{ marginRight: '0.08rem' }}>{props.text}</span>
      <CopyOutlined
        className={props.className || ''}
        title="复制"
        onClick={() => {
          setCopy(props.copyText || props.text)
        }}
      />
    </span>
  )
}
